//
//  VoiceViewModel.m
//  zhuchiren
//
//  Created by rainday on 15/2/8.
//  Copyright (c) 2015年 rainday. All rights reserved.
//

#import "VoiceViewModel.h"
#import <AFNetworking.h>
#import "IP.h"

@implementation VoiceViewModel

- (void)downLoadDataToFile:(id)filePath{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    id  token = [userDefaults objectForKey:@"token"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",token] forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    NSString *url = [NSString stringWithFormat:@"%s/voice",SERVER];
    
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[responseObject objectForKey:@"voice"]]];
        [data writeToURL:filePath atomically:YES];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       
    }];
    
    
}

- (void)upLoadData:(id)data{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    id  token = [userDefaults objectForKey:@"token"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",token] forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    
    
    NSString *url = [NSString stringWithFormat:@"%s/voice",SERVER];
    NSString *string = [NSString stringWithFormat:@"%@.aac",token];
    
    [manager POST:url  parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:data
                                    name:@"voice"
                                fileName:string
                                mimeType:@"audio/mpeg3"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];

}
@end
